<?php
/**
 * Created by : PhpStorm
 * User: godjarvis
 * Date: 2020/8/4
 * Time: 18:48
 */

namespace App\Model\Service;

use App\Bucket\Session\UserTrait;
use App\Bucket\Session\Userx;
use App\Bucket\Utils\MyToolkit;
use App\Model\Dao\CommissionDao;
use App\Model\Dao\DangKou\BillDao;
use App\Model\Dao\DangKou\OrderDao;
use App\Model\Dao\ShareTimesDao;
use App\Model\Dao\UserClientDao;
use App\Model\Dao\UserDao;
use App\Model\Entity\DangKou\Client;
use App\Model\Entity\ShareTimes;
use Fresh\Annotation\Autowired;
use Fresh\Foundation\Traits\Part\Encryptor;
use Fresh\Mvc\Model\Service;
use Fresh\Mvc\TokenSession;

class UserService extends Service
{
    use Encryptor, UserTrait;

    const SESSION_PERMISSION_USER = 'user';

    /**
     * @Autowired()
     * @var UserDao
     */
    public $userDao;

    /**
     * @Autowired()
     * @var ShareTimesDao
     */
    public $shareTimesDao;

    /**
     * @Autowired()
     * @var CommissionDao
     */
    public $commissionDao;

    /**
     * @Autowired()
     * @var UserClientDao
     */
    public $userClientDao;

    /**
     * @Autowired()
     * @var OrderDao
     */
    public $orderDao;

    /**
     * @Autowired()
     * @var BillDao
     */
    public $billDao;

    public function getUser()
    {
        $user = $this->getDI()->getSession()->get(self::SESSION_PERMISSION_USER);
        $userx = new Userx();
        if (!$user) {
            return $userx;
        }

        return MyToolkit::mapArrayToObjects($user, $userx);
    }

    public function login($username, $password)
    {
        $user = $this->userDao->getByAccountAndMobile($username);
        if (!$user) {
            $this->error('用户不存在');
        }

        $hash = $this->encryptor->encode($password, $user['password']);
        if (!$this->encryptor->isEqual($hash, $user['password'])) {
            $this->error('密码错误');
        }

        /** @var TokenSession $tokenSession */
        $tokenSession = $this->getDI()->getSession();
        $token = $tokenSession->issue($user['id'], [
            self::SESSION_PERMISSION_USER => $user
        ]);

        return [
            'token'      => $token,
            'expires_in' => $tokenSession->getLifetime(),
            'token_type' => 'bearer',
        ];
    }

    public function index()
    {
        // 分享次数
        $shareTimes = $this->shareTimesDao->get($this->user->id);

        //当月业绩
        $cids = $this->userClientDao->getUserCids($this->user->id);
        $month_achieve = $this->orderDao->getClientPayment($cids, date('Y-m-' . '01'), date('Y-m-d'));
        $month_refund = $this->billDao->getClientRefundAmount($cids, date('Y-m-' . '01'), date('Y-m-d'));

        // 历史业绩
        $total_achieve = $this->orderDao->getClientPayment($cids);
        $total_refund = $this->orderDao->getClientPayment($cids);

        // 当月佣金
        $month_commission = $this->commissionDao->getUserCommission($this->user->id, date('Y-m-' . '01'), date('Y-m-d'));

        // 历史佣金
        $total_commission = $this->commissionDao->getUserCommission($this->user->id);

        // 入驻档口网天数
        $days = MyToolkit::getDiffDateCount(date('Y-m-d', $this->user->created_at), date('Y-m-d'));

        return [
            'name'             => $this->user->name,
            'avatar'           => $this->user->avatar,
            'job'              => '档口网合伙人',
            'dk_times'         => ($shareTimes[ShareTimes::TYPE_PRODUCT] ?? 0) + ($shareTimes[ShareTimes::TYPE_MINI] ?? 0),
            'circle_times'     => $shareTimes[ShareTimes::TYPE_CIRCLE] ?? 0,
            'motto'            => $this->user->motto,
            'month_achieve'    => $month_achieve ?? 0,
            'month_refund'     => $month_refund ?? 0,
            'total_achieve'    => $total_achieve ?? 0,
            'total_refund'     => $total_refund ?? 0,
            'month_commission' => $month_commission ?? 0,
            'total_commission' => $total_commission ?? 0,
            'invitation_code'  => $this->user->invitation_code,
            'days'             => $days,
        ];
    }

    public function clientList($page, $limit)
    {
        $cids = $this->userClientDao->getUserCids($this->user->id);
        $paginator = $this->orderDao->getClientList($cids, $page, $limit);
        foreach ($paginator->items as &$item) {
            $item['client_type'] = Client::typeText()[$item['is_agent']];
            $item['month_achieve'] = $this->orderDao->getClientPayment($item['cid'], date('Y-m-' . '01'), date('Y-m-d')) ?? '0.00';
        }

        return $paginator;
    }
}